package com.briup.day21;

/*多线程通信次序无法控制 */
/**
*
* 多线程之间通信
* 2个生产者 3个消费者
* wait() notifyAll()
* for---while
*
* */
public class Test_Message {
    public static void main(String[] args) {
        Plate plate = new Plate();
        Thread th1=new Producer("厨师1",plate);
        Thread th2=new Producer("厨师2",plate);
        Thread c1=new Consumer("吃货1",plate);
        Thread c2=new Consumer("吃货2",plate);
        Thread c3=new Consumer("吃货3",plate);
        th1.start();
        th2.start();
        c1.start();
        c2.start();
        c3.start();
    }
}
//定义公共资源 盘子类
class Plate{
    //包子默认为0
    int num=0;

}
//生产者线程 生产包子 消费者线程 消费包子
class Producer extends Thread {
    private Plate plate;

    public Producer(String name, Plate plate) {
        super(name);
        this.plate = plate;
    }

    public void run() {
        int i=0;
        while (true) {
            i++;
        synchronized (plate) {
            //如果包子数量大于0 ，不生产，进入waiting状态
                while(plate.num>0){             //                if (plate.num > 0) {
                    try {
                        plate.wait();//会让消费者继续吃包子，然后再判断一下，没有包子了，再往下进行(挑出循环)，去继续生产
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("第" + i + "次" + this.getName() + "生产包子");
                plate.num++;
                System.out.println("生产完成，包子数量" + plate.num+"快来吃包子");
                //通知消费者线程操作num
                plate.notifyAll();
            }
        }
    }
}
class Consumer extends Thread {
    private Plate plate;

    public Consumer(String name, Plate plate) {
        super(name);
        this.plate = plate;
    }
    public void run() {
        int i=0;
        while (true) {
            i++;
            synchronized (plate) {
               while (plate.num == 0) {
                    try {
                        plate.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("第" + i + "次" + this.getName() + "吃包子");
                plate.num--;
                System.out.println("吃完包子，包子数量" + plate.num+"快来生产包子");
                //通知消费者线程操作num
                plate.notifyAll();
            }
        }
    }
}
//先创建好一批线程放着。有任务来了，就把任务交给池子里一个现成的空闲线程去做。任务做完，任务消失，但线程不死，回去等着接下一个任务。”